﻿using Se.Log;
using Se.Net.Sockets;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Se.Extend;
using Microsoft.CSharp;
using Se.Model;
using Se.Model.GMCommand;
using Se.Model.GameModel;
using Se.Data;
using System.Reflection;
using System.Data.SqlClient;
using Se.Model.Data;
using System.Diagnostics;
using Se.Thread;
using System.IO;
using Se.Common;
using Se.Model.Generator;
using Se.Protocol;

namespace SeServer
{
    class Program
    {
        static void Main(string[] args)
        {

            SocketSettings setting = new SocketSettings(10000, 100, 2000, 8024, new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9901), 1000, 5000);

            GameWorld.Initilize();
            GameWorld.Begin(setting);

            Console.WriteLine("输入空格继续");

            while (true)
            {
                var cmd = Console.ReadLine();
                switch (cmd)
                {
                    case "exit":
                        return;
                    case "save":
                        DataEntityFactory.SaveFactoryToDB(null);
                        break;
                }
            }
        }

        private static void TryReceive(Socket clientSocket)
        {
            byte[] data = new byte[8024];
            SocketAsyncEventArgs socketArgs = new SocketAsyncEventArgs();
            socketArgs.AcceptSocket = clientSocket;
            socketArgs.Completed += socketArgs_Completed;
            socketArgs.SetBuffer(data, 0, data.Length);
            clientSocket.ReceiveAsync(socketArgs);
        }

        static void socketArgs_Completed(object sender, SocketAsyncEventArgs args)
        {
            byte[] data = new byte[args.BytesTransferred];
            Buffer.BlockCopy(args.Buffer, args.Offset, data, 0, args.BytesTransferred);

            var commonMsg = ServerMessage.ParseFrom(data);
            Console.WriteLine(commonMsg.Chat.Message);

            TryReceive(args.AcceptSocket);
        }



        /// <summary>
        /// 获取初始的number
        /// </summary>
        /// <param name="number"></param>
        /// <param name="interval"></param>
        /// <returns></returns>
        public static int GetBasicNumber(int number, int interval = 20)
        {
            var numberRemain = number % interval;
            if (numberRemain == 0)
            {
                numberRemain = interval;
            }
            return number - numberRemain + 1;
        }

    }
}
